package cloudspace.vm.javassist.tests;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.Loader;
import javassist.NotFoundException;
import cloudspace.vm.javassist.ConfigurableTranslatorLoader;
import cloudspace.vm.javassist.Logger;
import cloudspace.vm.javassist.MalformedConfigurationException;
import cloudspace.vm.javassist.TranslatorProvider;
/**
 * NOT USED ANYMORE.  AVAILABLE FOR LEGACY USE.
 * @author mike
 *
 */
public class ByteCodeRuntime
{
	private Loader localClassLoader;
	private ClassPool localClassPool;
	private static TranslatorProvider eeFactory = TranslatorProvider
			.getExprEditorFactory();

	public ByteCodeRuntime()
			throws FileNotFoundException,
			NotFoundException
	{
		Logger.registerLogger("BCRError.log");
		localClassPool = ClassPool.getDefault();
		localClassPool.appendSystemPath();


		localClassLoader = new Loader(localClassPool);
		
		
		// localConfig = new XMLConfiguration(configFile);
	}
	public void addConfigFile(String configFile)
	{
		try
		{
		    File cFile = new File(configFile);
			eeFactory.addConfigFile(cFile, localClassPool);
		}
		catch (IOException e)
		{
			Logger.logInfo("Bad Configfile:  "
					+ configFile);
			e.printStackTrace();
		}
	}
	public void translateClasses() throws MalformedConfigurationException
	{

		List<ConfigurableTranslatorLoader> translators = eeFactory.getTranslators();
		for (Iterator<ConfigurableTranslatorLoader> translateIter = translators
				.iterator(); translateIter.hasNext();)
		{
			try
			{
				ConfigurableTranslatorLoader curTranslator = translateIter.next();
				localClassLoader.addTranslator(localClassPool, curTranslator);
			}
			catch( CannotCompileException e)
			{
				Logger.logInfo("A strange error occured when a translator was registered.");
			}
			catch(NotFoundException e)
			{
				Logger.logInfo("Strange error with Not Found Exception");
			}
		}

	}

	public Loader getLoader()
	{
		return localClassLoader;
	}

	public Class<?> loadClass(String className) throws CannotCompileException,
			NotFoundException, ClassNotFoundException
	{
		return localClassLoader.loadClass(className);
	}

	public ClassPool getClassPool()
	{
		return localClassPool;
	}
}
